<template>
    <div class="container-wrap">
        <img :src="myBackgroundImg" />
        <div class="background">
            <img v-if="showAwater" :src="PicUrl" class="avatar" @click="updateAwater" />
            <img v-else :src="oldAwaterImg" class="avatar" @click="updateAwater" />
            <span class="name">{{UserName}}</span>
        </div>
        <div class="my-list">
            <div class="line">
                <label for="name">姓名:</label>
                <input type="text" name="name" v-model="TrueName"  placeholder="请输入姓名">
            </div>
            <div class="line">
                <label>性别:</label>
                <div class="sex">
                    <section @click="params.Gender='男';sex = true;">
                        <van-checkbox :value="sex" checked-color="#ff9900">先生</van-checkbox>
                    </section>
                    <section @click="params.Gender='女';sex = false;" style="margin-left:50rpx;">
                        <van-checkbox :value="!sex" checked-color="#ff9900">女士</van-checkbox>
                    </section>
                </div>
            </div>
            <div class="line" v-if="RoleCode !== 'Leader'">
                <label for="grade">学段:</label>
                <div @click="show('grade')">{{GradeName}}</div>
            </div>
            <div class="line" v-if="RoleCode !== 'Leader'">
                <label for="subject">学科:</label>
                <div @click="show('subject')">{{SubjectName}}</div>
            </div>
            <div class="line" v-if="RoleCode === 'Expert'">
                <label for="title">职称:</label>
                <div @click="show('title')">{{PositionName}}</div>
            </div>
            <div class="line">
                <label for="title">区域:</label>
                <div @click="show('region')">{{RegionName}}</div>
            </div>
            <div class="line">
                <label for="address">地址:</label>
                <input type="text" name="address" v-model="UserCompany" placeholder="请输入地址">
            </div>

        </div>
        <div class="org_box">
            <span class="org_bot_cor"></span>
            点击图片即可修改头像
        </div>
        <button @click="save" class="save-button">保存修改</button>
        <div class="background-wraper" v-show="showWraper">
            <div class="region-select">
                <van-area v-if="showRegion" :area-list="areaList" :columns-num="3" title="区域" @confirm="Confirm" @cancel="showWraper = false">
                </van-area>
                <van-picker v-else-if="showGrade" show-toolbar title="学段" :columns="gradeList" @confirm="Confirm" @cancel="showWraper = false"/>
                <van-picker v-else-if="showSubject" show-toolbar title="学科" :columns="subjectList" @confirm="Confirm" @cancel="showWraper = false"/>
                <van-picker v-else-if="showTitle" show-toolbar title="职称" :columns="titleList" @confirm="Confirm" @cancel="showWraper = false"/>
            </div>
        </div>
        <van-toast id="van-toast" />
    </div>
</template>

<script>
    import {
        AppUserInfo, EditUserInfo,
        AppProvinceDataList, AppGradeDataList, AppSubjectDataList, AppPositionDataList
    } from '@/providers/service'
    import { dataEncoder, dataDecoder } from '@/providers/Func'
    // import areaList from '@/pages/register/Area'

    export default {
        name: 'my',
        data() {
            return {
                areaList: [],
                // 表单元素
                PicUrl: '',
                RoleCode: '',
                UserName: '',
                TrueName: '',
                sex: null,
                GradeName: '',
                SubjectName: '',
                PositionName: '',
                RegionName: '',
                UserCompany: '',
                // 控制流
                showAwater: true,
                showWraper: false,
                showGrade: false,
                gradeListRes: [],
                gradeList: [],
                showSubject: false,
                subjectListRes: [],
                subjectList: [],
                showTitle: false,
                titleListRes: [],
                titleList: [],
                showRegion: false,
                regionList: [],
                params: {},
                myBackgroundImg: `${process.env.PUBLICIIMGURL}base/myBackground.png`,
                oldAwaterImg: `${process.env.PUBLICIIMGURL}base/oldAwater.png`,
            }
        },
        methods: {
            judgeString(type) {
                return Object.prototype.toString.call(type) === '[object String]'
            },
            updateAwater() {
                let params = {}
                params.UserID = wx.getStorageSync('userInfo').UserID

                wx.chooseImage({
                    count: 1,  //最多可以选择的图片总数
                    sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                    success: res => {
                        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                        var tempFilePaths = res.tempFilePaths;
                        //启动上传等待中...
                        wx.showToast({
                            title: '正在上传...',
                            icon: 'loading',
                            mask: true,
                            duration: 10000
                        })

                        wx.uploadFile({
                            url: 'https://course.righthere.com.cn/API/UploadPic',
                            filePath: tempFilePaths[0],
                            name: 'PicUrl',
                            formData: {
                                data: dataEncoder(params)
                            },
                            header: {
                                "Content-Type": "multipart/form-data"
                            },
                            success: res => {
                                wx.hideToast();
                                let dataObj = dataDecoder(JSON.parse(res.data).Data)
                                if (dataObj.Status === '1') {
                                    let userInfo = wx.getStorageSync('userInfo')
                                    this.PicUrl = dataObj.Data.PicUrl
                                    userInfo.PicUrl = this.PicUrl
                                    wx.setStorageSync('userInfo', userInfo)
                                    this.$toast('上传图片成功')
                                } else {
                                    this.$toast('上传图片失败')
                                }
                            },
                            fail: res => {
                                wx.hideToast();
                                wx.showModal({
                                    title: '错误提示',
                                    content: '上传图片失败',
                                    showCancel: false,
                                    success: function (res) { }
                                })
                            }
                        })
                    }
                })

            },
            save() {
                let reg = new RegExp('^[\u4e00-\u9fa5]+$','g')
                if(!reg.test(this.TrueName)){
                    this.$toast('姓名必须为汉字')
                    return false
                }else{
                    if(this.TrueName.length < 2){
                        this.$toast('姓名长度必须大于2')
                        return false
                    }
                    // ID初始化
                    let params = this.params
                    let userInfo = wx.getStorageSync('userInfo')
                    if (params.hasOwnProperty('GradeID')) { } else {
                        this.params.GradeID = userInfo.GradeID
                    }
                    if (params.hasOwnProperty('SubjectID')) { } else {
                        this.params.SubjectID = userInfo.SubjectID
                    }
                    if (params.hasOwnProperty('PositionID')) { } else {
                        this.params.PositionID = userInfo.PositionID
                    }
                    if (params.hasOwnProperty('ProvinceID')) { } else {
                        this.params.ProvinceID = userInfo.ProvinceID
                    }
                    if (params.hasOwnProperty('CityID')) { } else {
                        this.params.CityID = userInfo.CityID
                    }
                    if (params.hasOwnProperty('DistrictID')) { } else {
                        this.params.DistrictID = userInfo.DistrictID
                    }
                    this.params.UserID = wx.getStorageSync('userInfo').UserID
                    this.params.TrueName = this.TrueName
                    this.params.Gender = this.sex ? '男' : '女'
                    this.params.UserCompany = this.UserCompany
//                    console.log(this.params)
                    this.EditUserInfoFn()
                }
            },
            show(label) {
                this.showWraper = true
                if (label === 'grade') {
                    this.showGrade = true
                    this.showSubject = false
                    this.showTitle = false
                    this.showRegion = false
                } else if (label === 'subject') {
                    if(this.GradeName !== '请选择学段'){
                        this.showSubject = true
                        this.showGrade = false
                        this.showTitle = false
                        this.showRegion = false
                    }else{
                        this.showWraper = false
                        this.$toast('请先选择学段')
                    }
                } else if (label === 'title') {
                    this.showTitle = true
                    this.showGrade = false
                    this.showSubject = false
                    this.showRegion = false
                } else if (label === 'region') {
                    this.showRegion = true
                    this.showGrade = false
                    this.showSubject = false
                    this.showTitle = false
                }
            },
            Confirm(event) {
                let target = event.target.value
                if (this.showGrade) {
                    this.params.GradeID = this.gradeListRes.filter(item => item.Name === target)[0].ID
                    this.GradeName = target
                    this.SubjectName = '请选择学科'
                    let temp = []
                    this.subjectListRes.filter(item => item.GradeName === this.GradeName).forEach(item=>{
                        temp.push(item.SubjectName)
                    })
                    this.subjectList = temp
                } else if (this.showSubject) {
                    this.params.SubjectID = this.subjectListRes.filter(item => item.SubjectName === target)[0].SubjectID
                    this.SubjectName = target
                } else if (this.showTitle) {
                    this.params.PositionID = this.titleListRes.filter(item => item.Name === target)[0].ID
                    this.PositionName = target
                } else if (this.showRegion) {
                    let selected = event.target.values
                    let provinceObj = this.regionList.filter(item => item.ProvinceName === selected[0].name)[0]
                    this.params.ProvinceID = provinceObj.ProvinceID
                    let cityObj = provinceObj.Citylist.filter(item => item.CityName === selected[1].name)[0]
                    this.params.CityID = cityObj.CityID
                    let DistrictObj = cityObj.Districtlist.filter(item => item.DistrictName === selected[2].name)[0]
                    this.params.DistrictID = DistrictObj.DistrictID
                    this.RegionName = `${selected[0].name} ${selected[1].name} ${selected[2].name}`
                }
                this.showWraper = false
            },

            async AppUserInfoFn() {
                try {
                    let params = {}
                    params.UserID = wx.getStorageSync('userInfo').UserID
                    let res = await AppUserInfo(params)
                    if (res) {
                        wx.setStorageSync('userInfo', res)
                        this.userInfoInit(res)
                    }
                } catch (err) {
                    console.log(err)
                }
            },
            async EditUserInfoFn() {
                try {
                    let res = await EditUserInfo(this.params)
                    if (!res.length) {
                        this.$toast('修改成功')
                    }
                } catch (err) {
                    console.log(err)
                }
            },

            async AppSubjectDataListFn() {
                try {
                    let res = await AppSubjectDataList()
                    this.subjectListRes = res
                } catch (err) {
                    console.log(err)
                }
            },

            async AppPositionDataListFn() {
                try {
                    let res = await AppPositionDataList()
                    this.titleListRes = res
                    this.titleListRes.forEach(item => {
                        this.titleList.push(item.Name)
                    })
                } catch (err) {
                    console.log(err)
                }
            },

            async AppProvinceDataListFn() {
                try {
                    let res = await AppProvinceDataList()
                    this.regionList = res
                } catch (err) {
                    console.log(err)
                }
            },

            async AppGradeDataListFn() {
                try {
                    let res = await AppGradeDataList()
                    this.gradeListRes = res
                    this.gradeListRes.forEach(item => {
                        this.gradeList.push(item.Name)
                    })
                } catch (err) {
                    console.log(err)
                }
            },

            userInfoInit(res) {
                // 表单可视元素初始化
                // 有头像就渲染，无头像就默认头像
                if (this.judgeString(res.PicUrl)) {
                    this.PicUrl = res.PicUrl
                    this.showAwater = true
                } else {
                    this.showAwater = false
                }
                this.UserName = res.UserName
                this.TrueName = res.TrueName
                this.sex = res.Gender === '男' ? true : false
                this.GradeName = this.judgeString(res.GradeName) ? res.GradeName : '请选择学段'
                this.SubjectName = this.judgeString(res.SubjectName) ? res.SubjectName : '请选择学科'
                this.PositionName = this.judgeString(res.PositionName) ? res.PositionName : '请选择职称'
                this.RegionName = this.judgeString(res.ProvinceName) ? `${res.ProvinceName} ${res.CityName} ${res.DistrictName}` : '请选择省市区'
                this.UserCompany = this.judgeString(res.UserCompany) ? res.UserCompany : ''

            },

            dataInit() {
                // 先查询数据展示出来
                this.AppUserInfoFn()
                this.AppGradeDataListFn()
                this.AppSubjectDataListFn()
                this.AppPositionDataListFn()
                this.AppProvinceDataListFn()
            },
        },
        onShow(){
            this.RoleCode = wx.getStorageSync('userInfo').RoleCode
        },
        mounted() {
            wx.request({
                url: 'https://course.righthere.com.cn/todu-project/todu-project/Area/Area.json',
                method: 'GET',
                header: {
                    'content-type': 'json'
                },
                success: (res) => {
                    this.areaList = res.data
                },
                fail: (err) => {
                    console.log(error)
                }
            })
            // 接口数据初始化
            this.dataInit()
        },
    }
</script>

<style lang="less" scoped>
    page {
        height: 100%;
        width: 100%;

    }

    .background-wraper {
        position: absolute;
        z-index: 10;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.2);

        .region-select {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
        }
    }

    .container-wrap {
        width: 100%;
        background: #FFF;

        img {
            width: 100%;
            height: 400rpx;
        }

        .save-button {
            width: 326rpx;
            height: 76rpx;
            line-height: 76rpx;
            margin-top: 86rpx;
            color: #FFF;
            background: #ff9900;
            font-size: 24rpx;
            border-radius: 0px;
        }

        .background {
            position: absolute;
            top: 0rpx;
            left: 0rpx;
            width: 100%;
            height: 400rpx;
            display: flex;
            flex-direction: column;
            align-items: center;

            .avatar {
                width: 164rpx;
                height: 164rpx;
                margin-top: 130rpx;
                background: transparent;
                border-radius: 50px;

                img {
                    width: 100%;
                    height: 100%;
                }
            }

            .name {
                margin-top: 12rpx;
                font-size: 32rpx;
                color: #FFF;
            }
        }

        .my-list {
            margin: 30rpx 40rpx 0rpx 40rpx;

            .line {
                height: 50rpx;
                display: flex;
                margin: 30rpx 0rpx;
                border-bottom: 1px solid #e9e9e9;
                font-size: 28rpx;
                font-family: Microsoft YaHei;
                color: #666;

                div {
                    margin-left: 30rpx;
                    width: 577rpx;
                }

                input {
                    position: relative;
                    left: 30rpx;
                    bottom: 8rpx;
                    width: 600rpx;
                }

                .sex {
                    display: flex;
                    flex-direction: row;
                    height: 60rpx;
                    margin-left: 30rpx;
                }
            }
        }
    }

    .org_box {
        position: absolute;
        left: 432rpx;
        top: 46rpx;
        width: 200rpx;
        height: 50rpx;
        line-height: 50rpx;
        margin-bottom: 60rpx;
        /*padding-left:2em;*/
        background: #FFF;
        color: #FF9900;
        font-size: 20rpx;
        padding: 0 20rpx;
    }

    .org_bot_cor {
        width: 0;
        height: 0;
        font-size: 0;
        border-width: 8rpx;
        border-style: solid;
        border-color: #FFF transparent transparent #FFF;
        _border-color: #f3961c white white;
        overflow: hidden;
        position: absolute;
        left: 0rpx;
        bottom: -15rpx;
    }
</style>
